package org.ring.common.transport;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @since 2024-07-15 20:46
 */
public class ByteBufOutputStream extends OutputStream {

    private final ByteBuf buf;
    private final int startIndex;

    public ByteBufOutputStream(ByteBuf buf) {
        this.buf = buf;
        this.startIndex = buf.writerIndex();
    }

    public int writtenBytes(){
        return buf.writerIndex() - startIndex;
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        if (len == 0) {
            return;
        }

        buf.writeBytes(b, off, len);
    }

    @Override
    public void write(byte[] b) throws IOException {
        buf.writeBytes(b);
    }

    @Override
    public void write(int b) throws IOException {
        buf.writeByte((byte) b);
    }
}
